import { UniqueConstraintError } from 'sequelize';
import { formatResponse } from '../utils/formatUtil';
import { Context, Next } from 'koa';

// 异常处理的中间件
const errorHandler = async (ctx: Context, next: Next) => {
  try {
    await next();
  } catch (err: any) {
    console.error('666', err);
    const { status = 400, message } = err;
    if (err instanceof UniqueConstraintError) {
      const error: UniqueConstraintError = err;
      ctx.status = 400;
      ctx.body = formatResponse(null, error.errors[0].message, 400);
    } else {
      ctx.status = status;
      ctx.body = formatResponse(null, message, status);
    }
  }
};

export default errorHandler;
